package com.zhoug.zmui;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.ReflectUtils;
import com.zhoug.common.utils.SoftInputMethodManager;
import com.zhoug.zmui.ints.OnSearchListener;
import com.zhoug.zmui.utils.ZMUIUtils;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;

/**
 * 搜索框
 * 全局样式定义:zmui_style_ZMUISearchView
 *  支持左右图标,清除图标,图标大小,个性化光标,背景,文字样式
 * @Author 35574
 * @Date 2020/7/30
 * @Description
 */
public class ZMUISearchView extends FrameLayout {
    private static final String TAG = ">>>ZMUISearchView";
    private static final boolean DEBUG = true;

    private EditText mEditText;
    private ImageView mLeftImage;
    private ImageView mRightImage;
    private ImageView mClearImage;
    private OnSearchListener onSearchListener;
    private @DrawableRes
    int leftIcon; //左边图标
    private @DrawableRes
    int rightIcon;//右边图标
    private @DrawableRes
    int clearIcon;//清除图标

    private int mDefHeight;//默认高度

    public ZMUISearchView(Context context) {
        this(context, null);
    }

    public ZMUISearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.zmui_style_ZMUISearchView);
    }

    public ZMUISearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    /**
     * 初始化
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZMUISearchView, defStyleAttr, R.style.zmui_style_ZMUISearchView);
        leftIcon = a.getResourceId(R.styleable.ZMUISearchView_zmui_leftIcon, ZMUIUtils.UN_USED_RES_ID);
        rightIcon = a.getResourceId(R.styleable.ZMUISearchView_zmui_rightIcon, ZMUIUtils.UN_USED_RES_ID);
        clearIcon = a.getResourceId(R.styleable.ZMUISearchView_zmui_clearIcon, ZMUIUtils.UN_USED_RES_ID);
        //背景
        int background = a.getResourceId(R.styleable.ZMUISearchView_zmui_background, ZMUIUtils.UN_USED_RES_ID);
        //光标
        int cursorDrawableRes = a.getResourceId(R.styleable.ZMUISearchView_zmui_textCursorDrawable, ZMUIUtils.UN_USED_RES_ID);
        //图片大小
        int iconSize = a.getDimensionPixelOffset(R.styleable.ZMUISearchView_zmui_iconSize, -1);
        float textSize = a.getDimension(R.styleable.ZMUISearchView_zmui_textSize, -1);
        int textColor = a.getColor(R.styleable.ZMUISearchView_zmui_textColor, ZMUIUtils.UN_USED_COLOR);
        int hintColor = a.getColor(R.styleable.ZMUISearchView_zmui_hintColor, ZMUIUtils.UN_USED_COLOR);
        String hintText = a.getString(R.styleable.ZMUISearchView_zmui_hintText);
        mDefHeight = a.getDimensionPixelOffset(R.styleable.ZMUISearchView_zmui_height, 0);
        int editTextMarginLeft = a.getDimensionPixelOffset(R.styleable.ZMUISearchView_zmui_editTextMarginLeft, 0);
        int editTextMarginRight = a.getDimensionPixelOffset(R.styleable.ZMUISearchView_zmui_editTextMarginRight, 0);

        a.recycle();
        if (mDefHeight <= 0) {
            mDefHeight = getContext().getResources().getDimensionPixelOffset(R.dimen.zmui_searchView_height);
        }

        View root = LayoutInflater.from(context).inflate(R.layout.zmui_search_view, this, false);
        //设置背景
        if (background != ZMUIUtils.UN_USED_RES_ID) {
            root.setBackgroundResource(background);
        }
        mLeftImage = root.findViewById(R.id.icon_left);
        mRightImage = root.findViewById(R.id.icon_right);
        mClearImage = root.findViewById(R.id.icon_clear);
        mEditText = root.findViewById(R.id.et_input);
        //设置图片尺寸
        if (iconSize > 0) {
            setImageSize(mLeftImage, iconSize);
            setImageSize(mRightImage, iconSize);
            setImageSize(mClearImage, iconSize);
        }
        //设置图片
        if (leftIcon != ZMUIUtils.UN_USED_RES_ID) {
            mLeftImage.setImageResource(leftIcon);
            mLeftImage.setVisibility(VISIBLE);
        } else {
            mLeftImage.setVisibility(GONE);
        }
        if (rightIcon != ZMUIUtils.UN_USED_RES_ID) {
            mRightImage.setImageResource(rightIcon);
            mRightImage.setVisibility(VISIBLE);
        } else {
            mRightImage.setVisibility(GONE);
        }
        //设置光标
        try {
            if(cursorDrawableRes!=ZMUIUtils.UN_USED_RES_ID){
                ReflectUtils.setDeclaredField(TextView.class,"mCursorDrawableRes",mEditText,cursorDrawableRes);
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        if (clearIcon != ZMUIUtils.UN_USED_RES_ID) {
            mClearImage.setImageResource(clearIcon);
        }
        if (DEBUG) {
            LogUtils.d(TAG, "init:leftIcon=" + leftIcon);
            LogUtils.d(TAG, "init:rightIcon=" + rightIcon);
            LogUtils.d(TAG, "init:clearIcon=" + clearIcon);
            LogUtils.d(TAG, "init:cursorDrawableRes=" + cursorDrawableRes);
        }


        //设置EditText和左右图标的距离
        ViewGroup.LayoutParams layoutParams = mEditText.getLayoutParams();
        if (layoutParams instanceof MarginLayoutParams) {
            MarginLayoutParams params = (MarginLayoutParams) layoutParams;
            params.leftMargin = editTextMarginLeft;
            params.rightMargin = editTextMarginRight;
            mEditText.setLayoutParams(params);
        }
        //设置文本样式
        ZMUIUtils.setTextColor(mEditText, textColor);
        ZMUIUtils.setTextSize(mEditText, textSize);
        ZMUIUtils.setHintTextColor(mEditText, hintColor);
        if (hintText != null) {
            mEditText.setHint(hintText);
        }
        addView(root);
        init();
    }


    /**
     * 设置图片尺寸
     *
     * @param imageView
     * @param iconSize
     */
    private void setImageSize(ImageView imageView, int iconSize) {
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        if (layoutParams != null) {
            layoutParams.width = iconSize;
            layoutParams.height = iconSize;
            imageView.setLayoutParams(layoutParams);
        }
    }


    /**
     * 软键盘按钮监听
     */
    private TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            int searchId = getResources().getInteger(R.integer.zmui_ime_search_id);
            if (actionId == searchId || actionId == EditorInfo.IME_ACTION_SEARCH) {
                startSearch();
                return true;
            }
            return false;
        }
    };

    /**
     * 监听
     */
    private void init() {
        mEditText.setOnEditorActionListener(onEditorActionListener);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && !s.toString().isEmpty()) {
                    //有输入的情况
                    //显示清除按钮
                    if (clearIcon != ZMUIUtils.UN_USED_RES_ID) {
                        if (mClearImage.getVisibility() != VISIBLE) {
                            mClearImage.setVisibility(VISIBLE);
                        }
                        //隐藏右边图片
                        if (mRightImage.getVisibility() == View.VISIBLE) {
                            mRightImage.setVisibility(GONE);
                        }
                    } else {
                        //没有清除按钮
                        if (rightIcon!=ZMUIUtils.UN_USED_RES_ID){
                            //显示右边图片
                            if (mRightImage.getVisibility() != View.VISIBLE) {
                                mRightImage.setVisibility(VISIBLE);
                            }
                        }
                    }
                } else {
                    //没有输入的情况
                    //隐藏清除按钮
                    if (mClearImage.getVisibility() == VISIBLE) {
                        mClearImage.setVisibility(GONE);
                    }
                    if(rightIcon!=ZMUIUtils.UN_USED_RES_ID){
                        //显示右边图片
                        if (mRightImage.getVisibility() != View.VISIBLE) {
                            mRightImage.setVisibility(VISIBLE);
                        }
                    }
                }
            }
        });
        //清除按钮监听
        mClearImage.setOnClickListener(v -> {
            mEditText.setText("");
        });

    }

    /**
     * 开始搜索
     * 可以主动调用,比如在页面上添加一个按钮,点击按钮调用开始搜索
     */
    public void startSearch() {
        if (mEditText != null) {
            mEditText.clearFocus();
        }
//        if (getContext() instanceof Activity) {
//            AppUtils.hideSoftKeyboard((Activity) getContext());
//        }
        //关闭软键盘
        new SoftInputMethodManager(getContext()).hideSoftInput(this);
        if (onSearchListener != null) {
            onSearchListener.onSearch(getInput());
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.AT_MOST) {
            int height = Math.min(mDefHeight + getPaddingTop() + getPaddingBottom(), MeasureSpec.getSize(heightMeasureSpec));
            if (DEBUG) {
                LogUtils.d(TAG, "onMeasure:height=" + height);
            }
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            int height = mDefHeight + getPaddingTop() + getPaddingBottom();
            if (DEBUG) {
                LogUtils.d(TAG, "onMeasure:height=" + height);
            }
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    /**
     * 设置搜索监听器
     *
     * @param onSearchListener
     */
    public void setOnSearchListener(OnSearchListener onSearchListener) {
        this.onSearchListener = onSearchListener;
    }

    /**
     * 设置提示文字
     *
     * @param hintText
     */
    public void setHintText(int hintText) {
        if (mEditText != null) {
            mEditText.setHint(hintText);
        }
    }

    /**
     * 设置输入的文字
     *
     * @param input
     */
    public void setInput(CharSequence input) {
        if (mEditText != null) {
            mEditText.setText(input);
        }
    }

    /**
     * 获取输入的文字
     *
     * @return
     */
    public String getInput() {
        if (mEditText != null) {
            return mEditText.getText().toString();
        }
        return "";
    }

    public EditText getEditText(){
        return mEditText;
    }

    public ImageView getLeftImage() {
        return mLeftImage;
    }

    public ImageView getRightImage() {
        return mRightImage;
    }

    public ImageView getClearImage() {
        return mClearImage;
    }

}
